<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="请假日期" prop="leaveDate">
        <el-date-picker clearable
          v-model="queryParams.leaveDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择请假日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="请假班次" prop="leaveShilf">
        <el-select v-model="queryParams.leaveShilf" placeholder="请选择请假班次" clearable>
          <el-option
            v-for="dict in shift_time"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="approvalStatus">
        <el-select v-model="queryParams.approvalStatus" placeholder="请选择审批状态" clearable>
          <el-option
            v-for="dict in audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="请假类型" prop="leaveType">
        <el-select v-model="queryParams.leaveType" placeholder="请选择请假类型" clearable>
          <el-option
            v-for="dict in leave_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="请假员工id" prop="leaveUid">
        <el-input
          v-model="queryParams.leaveUid"
          placeholder="请输入请假员工id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="员工名" prop="leaveUname" v-if="showUser">
        <el-input
          v-model="queryParams.leaveUname"
          placeholder="请输入请假员工名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="请假员工组id" prop="userGroupId">
        <el-input
          v-model="queryParams.userGroupId"
          placeholder="请输入请假员工组id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="组名" prop="userGroupName" v-if="showDept">
        <el-input
          v-model="queryParams.userGroupName"
          placeholder="请输入请假员工组名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="请假员工角色id" prop="userRoleId">
        <el-input
          v-model="queryParams.userRoleId"
          placeholder="请输入请假员工角色id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请假员工角色名" prop="userRoleName">
        <el-input
          v-model="queryParams.userRoleName"
          placeholder="请输入请假员工角色名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="showAdd">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['leave:leave:add']"
        >新增请假</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['leave:leave:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['leave:leave:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['leave:leave:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template #default="props">
          <div m="4">
            <el-table :data="props.row.approvalRecord ? JSON.parse(props.row.approvalRecord) : []" :border="childBorder">
              <el-table-column label="审批人角色" prop="roleName" />
              <el-table-column label="审批人名字" prop="userName" />
              <el-table-column label="审批留言" prop="message" />
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="${comment}" align="center" prop="id" /> -->
      <el-table-column label="请假日期" align="center" prop="leaveDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.leaveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假班次" align="center" prop="leaveShilf">
        <template #default="scope">
          <dict-tag :options="shift_time" :value="scope.row.leaveShilf"/>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="approvalStatus">
        <template #default="scope">
          <dict-tag :options="audit_status" :value="scope.row.approvalStatus"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="审批记录" align="center" prop="approvalRecord" /> -->
      <el-table-column label="请假理由" align="center" prop="leaveReason" />
      <el-table-column label="请假类型" align="center" prop="leaveType">
        <template #default="scope">
          <dict-tag :options="leave_type" :value="scope.row.leaveType"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="请假员工id" align="center" prop="leaveUid" /> -->
      <el-table-column label="员工名" align="center" prop="leaveUname" />
      <!-- <el-table-column label="请假员工组id" align="center" prop="userGroupId" /> -->
      <el-table-column label="组名" align="center" prop="userGroupName" />
      <!-- <el-table-column label="请假员工角色id" align="center" prop="userRoleId" /> -->
      <el-table-column label="岗位" align="center" prop="userRoleName" />
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button
            v-if="(this.postGroup !== '工厂普通员工') && (scope.row.leaveUid != user.userId)"
            :disabled="handleUpdateDisable(scope.row)"
            size="mini"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['leave:leave:edit']"
          >审批</el-button>
          <el-button
            v-if="scope.row.leaveUid == user.userId"
            :disabled="scope.row.approvalStatus!=='1'"
            size="mini"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['leave:leave:remove']"
          >撤销</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="请假日期" prop="leaveDate">
          <el-date-picker 
            clearable
            v-model="form.leaveDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择请假日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假班次" prop="leaveShilf">
          <el-select v-model="form.leaveShilf" placeholder="请选择请假班次">
            <el-option
              v-for="dict in shift_time"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="审批状态" prop="approvalStatus">
          <el-select v-model="form.approvalStatus" placeholder="请选择审批状态">
            <el-option
              v-for="dict in audit_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="请假理由" prop="leaveReason">
          <el-input v-model="form.leaveReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="请假类型" prop="leaveType">
          <el-select v-model="form.leaveType" placeholder="请选择请假类型">
            <el-option
              v-for="dict in leave_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="请假员工id" prop="leaveUid">
          <el-input v-model="form.leaveUid" placeholder="请输入请假员工id" />
        </el-form-item>
        <el-form-item label="请假员工名" prop="leaveUname">
          <el-input v-model="form.leaveUname" placeholder="请输入请假员工名" />
        </el-form-item>
        <el-form-item label="请假员工组id" prop="userGroupId">
          <el-input v-model="form.userGroupId" placeholder="请输入请假员工组id" />
        </el-form-item>
        <el-form-item label="请假员工组名" prop="userGroupName">
          <el-input v-model="form.userGroupName" placeholder="请输入请假员工组名" />
        </el-form-item>
        <el-form-item label="请假员工角色id" prop="userRoleId">
          <el-input v-model="form.userRoleId" placeholder="请输入请假员工角色id" />
        </el-form-item>
        <el-form-item label="请假员工角色名" prop="userRoleName">
          <el-input v-model="form.userRoleName" placeholder="请输入请假员工角色名" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" v-model="open2" width="500px" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="80px">
        <el-form-item label="审批留言" prop="message">
          <el-input type="textarea" v-model="form2.message" placeholder="请输入审批留言" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="approve">通 过</el-button>
        <el-button type="primary" @click="reject">驳 回</el-button>
        <!-- <el-button @click="cancel2">取 消</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLeave, getLeave, delLeave, addLeave, updateLeave } from "@/api/leave/leave";
import { getDicts } from '@/api/system/dict/data'
import { getUserProfile } from "@/api/system/user";
export default {
  name: "Leave",
  // dicts: ['leave_type', 'shift_time', 'audit_status'],
  data() {
    return {
      showAdd: true,
      showUser: true,
      showDept: true,
      postGroup: {},
      roleGroup: {},
      user: {},
      leave_type: [],
      audit_status: [],
      shift_time: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假记录表格数据
      leaveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 修改弹窗
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        leaveDate: null,
        leaveShilf: null,
        approvalStatus: null,
        leaveType: null,
        leaveUid: null,
        leaveUname: null,
        userGroupId: null,
        userGroupName: null,
        userRoleId: null,
        userRoleName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 修改表单参数
      form2: {},
      // 表单校验
      rules: {
        leaveDate: [
          { required: true, message: "请假日期不能为空", trigger: "blur" }
        ],
        leaveShilf: [
          { required: true, message: "请假班次不能为空", trigger: "change" }
        ],
        approvalStatus: [
          { required: true, message: "审批状态不能为空", trigger: "change" }
        ],
        leaveReason: [
          { required: true, message: "请假理由不能为空", trigger: "blur" }
        ],
        leaveType: [
          { required: true, message: "请假类型不能为空", trigger: "change" }
        ],
        leaveUid: [
          { required: true, message: "请假员工id不能为空", trigger: "blur" }
        ],
        leaveUname: [
          { required: true, message: "请假员工名不能为空", trigger: "blur" }
        ],
        userGroupId: [
          { required: true, message: "请假员工组id不能为空", trigger: "blur" }
        ],
        userGroupName: [
          { required: true, message: "请假员工组名不能为空", trigger: "blur" }
        ],
        userRoleId: [
          { required: true, message: "请假员工角色id不能为空", trigger: "blur" }
        ],
        userRoleName: [
          { required: true, message: "请假员工角色名不能为空", trigger: "blur" }
        ],
      },
      // 修改表单校验
      rules2: {
        message: { required: true, message: "审批留言不能为空", trigger: "blur" }
      }
    };
  },
  created() {
    this.getUser()
    this.getDicts("shift_time")
    this.getDicts("leave_type")
    this.getDicts("audit_status")
    // this.getList();
  },
  methods: {
    handleUpdateDisable(row) {
      if(row.approvalStatus==='1') {
        if(this.postGroup === "老板" && (row.userRoleName === '工厂组长' || row.userRoleName === '办公室')) {
         return false
        }
        if(this.postGroup === "工厂组长" && row.userRoleName === '工厂普通员工') {
          return false
        }
      }
      if(row.approvalStatus==='2') {
        if(this.postGroup === "老板") {
          return false
        }
      }
      return true
    },
    // 同意
    approve() {
      const record = {
        userName: this.user.userName,
        roleName: this.postGroup,
        message: this.form2.message
      }
      const recordList = this.form.approvalRecord ? JSON.parse(this.form.approvalRecord) : []
      recordList.push(record)
      const postData = {
        id: this.form.id,
        approvalStatus: this.postGroup === "老板"?'3':'2',
        approvalRecord: JSON.stringify(recordList)
      }
      updateLeave(postData).then(response => {
        this.$modal.msgSuccess("审批成功");
        this.open2 = false;
        this.getList();
      });
    },
    // 不同意
    reject() {
      const record = {
        userName: this.user.userName,
        roleName: this.postGroup,
        message: this.form2.message
      }
      const recordList = this.form.approvalRecord ? JSON.parse(this.form.approvalRecord) : []
      recordList.push(record)
      const postData = {
        id: this.form.id,
        approvalStatus: "4",
        approvalRecord: JSON.stringify(recordList)
      }
      updateLeave(postData).then(response => {
        this.$modal.msgSuccess("审批成功");
        this.open2 = false;
        this.getList();
      });
    },
    getUser() {
       getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
        // if(this.roleGroup==="工厂") {
        //   this.showDept = false
        //   this.queryParams.groupName = this.user.dept.deptName
        // }else{
        //   this.getDeptList()
        // }
        if(this.postGroup === "工厂组长") {
          this.showDept = false
          this.queryParams.userGroupName = this.user.dept.deptName
        } else if(this.postGroup === "老板") {
          this.showAdd = false
        } else {
          this.showDept = false
          this.showUser =false
          this.queryParams.leaveUid = this.user.userId
          this.queryParams.userGroupName = this.user.dept.deptName
        }
        
        this.getList();
      });
    },
    // 班次字典
    async getDicts(type) {
      const res = await getDicts(type)
      const data = res.data.map(item => {
        return {
          ...item,
          label: item.dictLabel,
          value: item.dictValue
        }
      })
      this[type] = data
    },
    /** 查询请假记录列表 */
    getList() {
      this.loading = true;
      listLeave(this.queryParams).then(response => {
        this.leaveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        leaveDate: null,
        leaveShilf: null,
        approvalStatus: null,
        approvalRecord: null,
        leaveReason: null,
        leaveType: null,
        leaveUid: null,
        leaveUname: null,
        userGroupId: null,
        userGroupName: null,
        userRoleId: null,
        userRoleName: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 表单重置
    reset2() {
      this.form2 = {
        id: null,
        message: null
      };
      this.resetForm("form2");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加请假记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset2();
      const id = row.id || this.ids
      getLeave(id).then(response => {
        this.form = response.data;
        this.open2 = true;
        this.title = "审批请假记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLeave(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const postData = {
              ...this.form,
              approvalStatus: '1',
              leaveUid: this.user.userId,
              leaveUname: this.user.userName,
              userGroupId: this.user.dept.deptId,
              userGroupName: this.user.dept.deptName,
              // userRoleId: this.user.roles[0].roleId,
              userRoleName: this.postGroup,
            }
            addLeave(postData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除请假记录编号为"' + ids + '"的数据项？').then(function() {
        return delLeave(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('leave/leave/export', {
        ...this.queryParams
      }, `leave_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
